<?php

/**
 * This is the model class for table "{{message}}".
 *
 * The followings are the available columns in table '{{message}}':
 * @property integer $id
 * @property string $module
 * @property integer $module_id
 * @property string $sender_name
 * @property string $sender_email
 * @property string $contact_number
 * @property string $subject
 * @property string $message
 * @property integer $status_code
 * @property string $create_timezone
 * @property string $create_timestamp
 * @property string $create_datetime
 * @property string $create_date
 * @property string $create_time
 * @property integer $create_by
 * @property string $update_timezone
 * @property string $update_timestamp
 * @property string $update_datetime
 * @property string $update_date
 * @property string $update_time
 * @property integer $update_by
 */
class Message extends ActiveRecord {

    public $moduleId_;
    public $module_;
    public $name_;
    public $email_;
    public $contactNumber_;
    public $subject_;
    public $message_;
    public $status_;

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return Enquiry the static model class
     */
    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return '{{message}}';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('name_, email_, contactNumber_, subject_, message_', 'filter', 'filter' => 'trim'),
            //array('name_, subject_, message_','filter','filter'=>array($obj=new CHtmlPurifier(),'purify')),
            
            array('name_, email_, message_', 'required', 'on' => 'userCreate, update'),
            array('name_', 'length', 'max' => 100),
            array('email_', 'length', 'max' => 50),
            array('email_', 'email', 'checkMX' => false),
            
            array('contactNumber_', 'length', 'max' => 15),
            array('contactNumber_', 'ext.validators.ContactNumberValidator'),
            
            array('name_, email_, contactNumber_, subject_, message_', 'safe', 'on' => 'userCreate, update'),
            
            array('id_', 'safe', 'on' => 'search'),
            
            array('captcha_', 'required', 'on' => 'userCreate'),
            array('captcha_', 'ext.widgets.captchaExtended.CaptchaExtendedValidator', 'allowEmpty' => !CCaptcha::checkRequirements(), 'on' => 'userCreate'),
            array('captcha_', 'safe', 'on' => 'userCreate'),
            
            //compulsory
            array('var_', 'ext.validators.BotDetectionValidator'),
            array('var_', 'safe'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'creator' => array(self::BELONGS_TO, 'User', 'create_by'),
            'editor' => array(self::BELONGS_TO, 'User', 'update_by'),
            'recipient' => array(self::BELONGS_TO, 'User', 'recipient_id'),
            
            'senderAccount'=> array(self::BELONGS_TO, 'Account', 'sender_account_id', 'scopes'=>array('accessible')),
            'recipientAccount'=> array(self::BELONGS_TO, 'Account', 'recipient_account_id', 'scopes'=>array('accessible')),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'id_' => Lang::t('message.lbl.id'),
            'name_' => Lang::t('message.lbl.name'),
            'email_' => Lang::t('message.lbl.email'),
            'contactNumber_' => Lang::t('message.lbl.contact.number'),
            'subject_' => Lang::t('message.lbl.subject'),
            'message_' => Lang::t('message.lbl.message'),
            'captcha_' => Lang::t('captcha.lbl'),
        );
    }
   
    public function scopes() {
        $t = $this->getTableAlias(false);
        return array(
            'accessible'=>array(
                'condition' => $t.'.status_code <> :deletedStatus'.$t,
                'params' => array(
                    ':deletedStatus'.$t => Option::STATUS_DELETED,
                ),
            ),
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function adminSearch() {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.
        $t = $this->getTableAlias(false);
        $criteria = new CDbCriteria;

        $criteria->compare($t.'.id', $this->id_, true);
        $criteria->compare('LOWER('.$t.'.sender_name)', $this->name_, true);
        $criteria->compare('LOWER('.$t.'.sender_email)', $this->email_, true);
        $criteria->compare('LOWER('.$t.'.subject)', strtolower($this->subject_), true);
        $criteria->compare($t.'.contact_number', $this->contactNumber_, true);
        $criteria->addSearchCondition('LOWER('.$t.'.message)', strtolower($this->message_), true);

        $sort = new CSort;
        $sort->sortVar = 'sort_';
        $sort->multiSort = true;
        $sort->defaultOrder = implode(', ', array(
            $t.'.id DESC',
        ));

        return new ActiveDataProvider($this->accessible(), array(
            'criteria' => $criteria,
            'sort' => $sort,
            'pagination' => array(
                'pageSize' => Yii::app()->request->getParam('pageSize_', $this->pageSize_),
                'pageVar' => 'page_',
            ),
        ));
    }

    public function getSubjectOption($id = null) {
        $option = array(
            1 => Lang::t('message.lbl.general.enquiry'),
            2 => Lang::t('message.lbl.new.offer'),
        );
        return empty($id) ? $option : $option[$id];
    }
    
    public function autoFill(){
        switch ($this->scenario) {
            case 'userCreate':
                $this->status_ = Option::STATUS_NEW;
                if (!Yii::app()->user->isGuest) {
                    $this->name_ = Yii::app()->user->fullName;
                    $this->email_ = Yii::app()->user->email;
                    $this->contactNumber_ = Yii::app()->user->contactNumber;
                }//end if
                break;
        }//end switch
    }

    protected function afterValidate() {
        parent::afterValidate(); //must call parent function
    }

    protected function beforeSave() {
        if (parent::beforeSave()) {
            if ($this->isNewRecord) {
                $this->module_id = $this->moduleId_;
                $this->module = strtolower($this->module_);
                $this->sender_name = $this->name_;
                $this->sender_email = $this->email_;
                $this->contact_number = $this->contactNumber_;
                $this->subject = $this->getSubjectOption($this->subject_);
                $this->message = $this->message_;

                $this->status_code = $this->status_;
                $this->setCreateDateTime();
            } else {
                $this->setUpdateDateTime();
            }
            return true;
        }
        else
            return false;
    }

    protected function afterSave() {
        parent::afterSave();
        
        $this->saveLog();
    }

    public function addRecord() {
        $this->dataLog[get_class($this)]=$this->attributes;
        return $this->save(true);
    }

    public function updateRecord() {
        switch ($this->scenario) {
            case 'adminUpdate':
                $this->status_code = $this->status_;
                break;
        }
        $this->dataLog[get_class($this)]=$this->attributes;
        return $this->save(true);
    }

    public function deleteRecord() {
        $this->status_code = Option::STATUS_DELETED;
        $this->dataLog[get_class($this)]=$this->attributes;
        return $this->save(true);
    }

    public function getProfileId() {
        return empty($this->creator) ? null : $this->creator->id;
    }

    public function getSenderName() {
        return $this->sender_name;
    }

    public function getSenderContactNumber() {
        return $this->contact_number;
    }

    public function getSenderEmail() {
        return $this->sender_email;
    }

}//end class